package com.demo.controller;

import com.demo.model.JsonViewVo;
import com.demo.model.User;
import com.demo.service.UserService;
import com.fasterxml.jackson.annotation.JsonView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;
import java.util.UUID;

/**
 * @Auther: luobiao
 * @Date: 2020/5/22 07:47
 * @Description: 提交方式为json对象
 */
@RestController
@RequestMapping("user/json")
public class JsonUserConroller {
    @Autowired
    UserService userService;

    @InitBinder
    public  void initBinder(WebDataBinder binder, HttpServletRequest request){
        binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),false));
    }

    //MyAdvice中设置性别默认值为0表是是woman,controller中设置是man，最终使用的是Advice中的model，因为Advice中优先级更高
    @ModelAttribute
    public User modelAttributeUser(){
        User user =new User();
        user.setSex("man");
        return user;
    }

    /**
     http://localhost:8080/user/json/add
     {
     "name":"luobiao",
     "age":"34"
     }
     **/
    @RequestMapping("/add")
    public String add(@RequestBody User user, ModelMap modelMap){

        user.setId(UUID.randomUUID().toString());
        userService.addUser(user);
        return "success";
    }

    /**
     http://localhost:8080/user/json/jsonView
    {
      "field1":"field1",
      "field2":"field2",
      "field3":"field3",
      "field4":"field4"
    }
     **/
    @PostMapping("/jsonView")
    public JsonViewVo jsonView(@JsonView(JsonViewVo.Component1.class) @RequestBody JsonViewVo jsonViewVo){
        //虽然传入的有参数中有field1，field2，field3，field4。但只会处理field1，field2，field3，因为Component1只标注在这三个字段上
        System.out.println(jsonViewVo);
        return jsonViewVo;
    }

}
